import random
import string

from django.core.mail import send_mail
from django.db.models import Q
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse, JsonResponse
from .models import User, Follow,Captcha
from django.views.decorators.http import require_http_methods


# Create your views here.
def checklogin(func):
    def check(request, *args):
        # 从session中获取username
        username = request.session.get('username')
        # 判断username是否存在
        if username:
            # 存在就跳到相应的界面
            return func(request, *args)
        else:
            # 不存在则跳到登陆界面
            return redirect(reverse('auth:userlogin'))

    return check


def userlogin(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = User.objects.filter(Q(username=username) & Q(password=password) |
                                   Q(email=username) & Q(password=password) |
                                   Q(tel=username) & Q(password=password)).first()
        if user:
            # return HttpResponse("登录成功")
            # 设置session
            request.session['id'] = user.id
            request.session['username'] = user.username
            # 获取session
            # request.session.get()
            # 清除session
            # request.session.flush()

            return redirect(reverse('index'))
        else:
            return HttpResponse("登录失败")

# 发送验证码
def send_mail_captcha(request):
    email = request.GET.get('email')
    user = User.objects.get(email=email)
    if not email:
        return JsonResponse({'code': 400, 'message': '必须传递邮箱'})
    # 生成验证码（随机四位数）
    captcha = "".join(random.sample(string.digits,4))
    # 把生成的验证码放入数据库中，如果这个邮箱的验证码已存在，删除并重新创建，不存在创建发送
    Captcha.objects.update_or_create(email=user,defaults={'captcha':captcha})
    send_mail("发送验证码",message=f"你的验证码：{captcha}",recipient_list=[email],from_email=None)
    print(captcha)
    return JsonResponse({'code':200,'mseeage':'发送成功'})

# 验证码登录
def captcha_login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        email = request.POST.get('email1')
        captcha = request.POST.get('captcha')
        emaill = User.objects.filter(email=email).first()
        if not emaill:
            return HttpResponse("邮箱错误")
        if emaill.check_captcha(captcha):
            return JsonResponse({'code':200,'msg':"登陆成功"})



def userregister(request):
    # return render(request, 'register.html')
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        username = request.POST.get('username')
        tel = request.POST.get('phone')
        tell = User.objects.filter(Q(tel=tel)).first()
        password = request.POST.get('password')
        email = request.POST.get('email')
        emaill= User.objects.filter(Q(email=email)).first()
        if emaill:
            return HttpResponse("邮箱已存在")
        if tell:
            return HttpResponse("手机号已存在")
        user = User()
        user.username = username
        user.tel = tel
        user.password = password
        user.email = email
        # return HttpResponse("注册成功")
        user.save()
        context = {
            'user': user
        }
        return render(request, 'next_reg.html', context)


def usernext_reg(request):
    if request.method == 'GET':
        return render(request, 'next_reg.html')
    if request.method == 'POST':
        id = request.POST.get('user_id')
        user = User.objects.get(pk=id)
        icon = request.FILES.get('icon')
        print(icon)
        birth = request.POST.get('birth')
        nickname = request.POST.get('nickname')
        realname = request.POST.get('realname')
        # status = request.POST.get('status')
        sex = request.POST.get('sex')
        user.icon = icon
        user.birth = birth
        user.nickname = nickname
        user.realname = realname
        user.sex = sex
        user.save()
        # return HttpResponse("提交成功")
        context = {
            'user': user
        }
        return render(request, 'success.html', context)


def usersuccess(request):
    return render(request, 'success.html')


def userlogout(request):
    res = redirect(reverse('index'))
    request.session.clear()
    return res


def userfindpass(request):
    if request.method == 'GET':
        # 如果是 GET 请求，渲染并返回 'findpass.html' 模板
        return render(request, 'findpass.html')
    else:
        # 如果是 POST 请求，处理找回密码逻辑
        username = request.POST.get('username')
        email = request.POST.get('email')
        user = User.objects.filter(Q(username=username) & Q(email=email)).first()
        if user:
            return HttpResponse(user.password)
        else:
            return HttpResponse("账户或邮箱错误")


@require_http_methods(["GET", "POST"])
@checklogin
def userpersonal(request):
    if request.method == 'GET':
        userid = request.session.get("id")
        user = User.objects.get(pk=userid)
        # oldemail = request.POST.get("oldemail")
        # newemail = request.POST.get("newemail")
        # oldname = User.objects.filter(Q(email=oldemail)).first()
        # if not oldname :


        follow_list = list(Follow.objects.filter(userId=userid).all())
        by_follow_list = list(Follow.objects.filter(followId=userid).all())
        # context={
        #     'follow_list': follow_list,
        #     'by_follow_list':by_follow_list
        # }
        return render(request, 'personal.html', locals())


def usermodifypass(request):
    if request.method == 'GET':
        return render(request, 'modifypass.html')
    else:
        id = request.session.get('id')
        user = User.objects.get(pk=id)
        pw = user.password
        password = request.POST.get('password')
        onepassword = request.POST.get('onepassword')
        twopassword = request.POST.get('twopassword')
        if password != pw:
            return HttpResponse("旧密码输入错误")
        if onepassword != twopassword:
            return HttpResponse("两次新密码不一致")
        user.password = onepassword
        user.save()
        return HttpResponse("修改成功")


@require_http_methods(["GET", "POST"])
def userattention(request):
    if request.method == 'GET':
        userid = request.session.get('id')
        # 自己关注的用户
        follow_list = list(Follow.objects.filter(userId=userid).all())
        # 有多少粉丝关注我
        by_follow_list = list(Follow.objects.filter(followId=userid).all())

        context = {"follow_list": follow_list, "by_follow_list": by_follow_list}
        return render(request, 'attention.html', context=context)


@require_http_methods(["GET", "post"])
def concern(request, id):
    # 获取当前登录的个人id
    userid = request.session.get('id')
    # 根据在session中获取的id找到数据库中的用户
    user = User.objects.get(pk=userid)
    # 更具路由传来的id获取页面用户
    followUser = User.objects.get(pk=id)
    # 判断两个用户是否在Follow表中
    user_follow = Follow.objects.filter(userId=user, followId=followUser).first()
    if user_follow:
        user_follow.delete()
        return JsonResponse({"msg": "取消关注成功"})
    else:
        Follow.objects.create(userId=user, followId=followUser)
        return JsonResponse({"msg": "关注成功"})
